package edu.corn.common.util;

import java.lang.reflect.Field;

public class ReflectionUtil {

    // 根据类型获取属性值
    public static <T> T getByType(Object obj, Class<T> fieldType) {
        for (Field field : obj.getClass().getDeclaredFields()) {
            if (field.getType().equals(fieldType)) {
                field.setAccessible(true);
                try {
                    return (T) field.get(obj);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Failed to access field", e);
                }
            }
        }
        return null; // 如果没有找到
    }

    // 根据类型设置属性值
    public static void setByType(Object obj, Class<?> fieldType, Object value) {
        for (Field field : obj.getClass().getDeclaredFields()) {
            if (field.getType().equals(fieldType)) {
                field.setAccessible(true);
                try {
                    field.set(obj, value);
                    return; // 设置成功后返回
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Failed to set field value", e);
                }
            }
        }
        throw new RuntimeException("No field found for type: " + fieldType.getName());
    }
}
